package controller;

import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;

import network.DownloaderTCPClient;
import network.LocalNetworkSettings;
import network.TCPChatNIServer;

public class TCPServerController extends GenericController {

	private static TCPServerController instance = null;
	
	public ArrayBlockingQueue<Socket> newClients;
	
	private GUIController guicontroller;
	private TCPChatNIServer server;
	private boolean isrunning;
	
	private TCPServerController() {
		super();
		this.guicontroller = GUIController.getInstance();
		newClients = new ArrayBlockingQueue<Socket>(10);
	}
	
	public static TCPServerController getInstance()
	{
		if(instance == null)
			instance = new TCPServerController();
		
		return instance;
	}

	@Override
	public void run() {
		isrunning = true;
		Socket sockclient = null;
		
		guicontroller.writeDebugScreen("TCPServerController > launched\n");
		
		// launching of TCP server
		server  = new TCPChatNIServer(LocalNetworkSettings.LOCAL_TCP_SERVER_PORT);
		(new Thread(server)).start();
		
		while(isrunning)
		{
			try
			{
				sockclient = newClients.take();
			}
			catch(InterruptedException e)
			{}
			
			// on verifie si la socket est connecte, sinon cela signifie certainement qu'on veut killer le server
			// dans le cas contraire, c'est juste que le client a déjà fermé la connection
			if( sockclient.isConnected() )
			{
				(new Thread(new DownloaderTCPClient(sockclient))).start();
				guicontroller.writeDebugScreen("TCPServerController > new downloaderTCPclient launched\n");
			}
		}
		
		guicontroller.writeDebugScreen("TCPServerController > shut down\n");
	}
	
	public void kill()
	{
		server.kill();
		isrunning = false;
		newClients.clear();
		// on envoie une socket non connectée pour arrêter le server
		newClients.add(new Socket());
	}
}
